package com.vipboot.platform.system.listener;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vipboot.framework.biz.api.auth.event.UpdateLoginInfoEvent;
import com.vipboot.platform.system.crud.dao.SysUserDao;
import com.vipboot.platform.system.domain.entity.SysUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

@RequiredArgsConstructor
@Slf4j
@Component
public class UpdateLoginInfoEventListener {

    private final SysUserDao sysUserDao;

    /**
     * 更新登录信息
     */
    @Async
    @EventListener
    public void onUpdateLoginInfoEvent(UpdateLoginInfoEvent event) {
//        SysUser sysUser = new SysUser();
//        sysUser.setUserId(event.getUserId());
//        sysUser.setLoginIp(event.getIp());
//        sysUser.setLoginDate(new Date());

        LambdaUpdateWrapper<SysUser> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(SysUser::getLoginIp, event.getIp());
        updateWrapper.set(SysUser::getLoginDate, new Date());
        updateWrapper.eq(SysUser::getUserId, event.getUserId());
        sysUserDao.update(updateWrapper);

        // 不执行 更新数据 UpdateListener
//        EntityListenerManager.withoutUpdateListener(() -> {
//            sysUserDao.updateById(sysUser);
//        });
    }
}
